首先我們要在info裡加入相機的權限歐
override func viewDidLoad() {
super.viewDidLoad()
// 設置 view 的 delegate
sceneView.delegate = self
// 展示 debug 訊息(可選)
sceneView.showsStatistics = true
// 創建新的場景
let scene = SCNScene()
sceneView.scene = scene
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
sceneView.addGestureRecognizer(tapGestureRecognizer)
// 創建AR世界追蹤的配置
let configuration = ARWorldTrackingConfiguration()
// 啟動 session
sceneView.session.run(configuration)
}
@objc func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
// 獲取點擊位置
let location = gestureRecognizer.location(in: sceneView)
// 射線檢測
let hitTestResults = sceneView.hitTest(location, types: .featurePoint)
if let hitResult = hitTestResults.first {
// 創建方塊
let cube = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
let cubeNode = SCNNode(geometry: cube)
// 設置方塊位置
cubeNode.position = SCNVector3(
x: hitResult.worldTransform.columns.3.x,
y: hitResult.worldTransform.columns.3.y,
z: hitResult.worldTransform.columns.3.z
)
// 添加方塊到場景
sceneView.scene.rootNode.addChildNode(cubeNode)
}
這樣你就完成點擊畫面會產生一個方塊